//
//  ViewController.m
//  SWSerialPortTool
//
//  Created by mt-007 on 2021/4/10.
//

#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // init serial
    serial = [[SWSerial alloc] init];
    
    // setting flag is 0 - everything is ok
    FLAG = 0;
    
    // get and send to combo box the device list
    NSArray *arr = [SWDevSearch searchDeviceOutArray:@"/dev/"];
    [_deviceChoose_comboBox addItemsWithObjectValues:arr];

    // disable disconnectButton.
    //[_disconnectButton setEnabled:FALSE];
    _disconnectButton.enabled = NO;
}

#pragma mark - Personal Code for View Controller
/**
 * @brief Get base information from each combo box, and start to connect the device.
 */
- (IBAction)connectDeviceClick:(id)sender {
    // Check device status
    FLAG = 0;
    
    // Get base info
    NSString *baudRate = [_baudRate_comboBox stringValue];
    NSString *dataBit = [_dataBit_comboBox stringValue];
    NSString *checkParity = [_checkParity_comboBox stringValue];
    NSString *stopBit = [_stopBit_comboBox stringValue];
    
    // Check info is empty.
    if([baudRate isEqual:@""]) {
        NSString *infoEmptyBaudRate = @"-- Error: baud rate is empty\n";
        [self displayStringToConsole:infoEmptyBaudRate];
        FLAG = 1;
    }
    
    if([dataBit isEqual:@""]) {
        NSString *infoEmptyDataBit = @"-- Error: data bit is empty\n";
        [self displayStringToConsole:infoEmptyDataBit];
        FLAG = 1;
    }
    
    if([checkParity isEqual:@""]) {
        NSString *infoEmptyCheckParity = @"-- Error: check parity is empty\n";
        [self displayStringToConsole:infoEmptyCheckParity];
        FLAG = 1;
    }
    
    if([stopBit isEqual:@""]) {
        NSString *infoEmptyStopBit = @"-- Error: stop bit is empty\n";
        [self displayStringToConsole:infoEmptyStopBit];
        FLAG = 1;
    }
    
    
    NSLog(@"Connect info:%@ %@ %@ %@", baudRate, dataBit, checkParity, stopBit);
    
    
    // get device
    NSString *deviceChoose = [_deviceChoose_comboBox stringValue];
    if([deviceChoose isEqual:@"设备选择"]) {
        NSString *infoDeviceChoose = @"-- Error: Not choose device.\n";
        [self displayStringToConsole:infoDeviceChoose];
        FLAG = 1;
    }
    
    if(FLAG == 0) {
        // serial open
        fd = [serial serialOpen:deviceChoose];
        
        int toBaudRate = [baudRate intValue];
        int toDataBit = [dataBit intValue];
        char toCheckParity = [checkParity characterAtIndex:0];
        int toStopBit = [stopBit intValue];
        
        // serial config
        [serial serialConfig:fd
                 andBaudRate:toBaudRate
                  andDataBit:toDataBit
              andCheckParity:toCheckParity
                  andStopBit:toStopBit];
        [_disconnectButton setEnabled:TRUE];
        [_connectButton setEnabled:FALSE];
        
        [self displayStringToConsole:[NSString stringWithFormat:@"Connect :%@",[serial returnSerialStatusByNSString]]];
        FLAG = 2;
    }
}



/**
 * @brief Disconnect serial port device.
 */
- (IBAction)disconnectDeviceClick:(id)sender {
    [serial serialClose:fd];
    [_connectButton setEnabled:TRUE];
    [_disconnectButton setEnabled:FALSE];
    [self displayStringToConsole:@"Disconnect.\n"];
    FLAG = 0;
}


/**
 * @brif Send message and read message, and as a consquence, to record information.
 */
- (IBAction)sendMessageClick:(id)sender {
    [self sendMessage];
}



/**
 * @brief clear console.
 */
- (IBAction)clearConsoleClick:(id)sender {
    [__consoleTextView.textStorage setAttributedString:[[NSAttributedString alloc] initWithString:@""] ];
}


/**
 * @brief Test function, it will remove at next and next and next gen.
 */
- (IBAction)testClick:(id)sender {
    NSArray *arr = [SWDevSearch searchDeviceOutArray:@"/dev/"];
    NSLog(@"%@, - FLAG = %d", arr, FLAG);
    [_TestButton setEnabled:FALSE];
}


- (IBAction)testSender:(id)sender {
    //[self displayStringToConsole:@"wwwwwww\n"];
    [self sendMessage];
}


- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];

    // Update the view, if already loaded.
}




#pragma mark - ViewController self function.

/**
 * @brief Display a NSString to console(table view), use simplify string become attributed string.
 * As a consequence, it will send to __consoleTextView and NSLog.
 */
- (void)displayStringToConsole:(NSString *)displayString {
    
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:displayString];
    
    [__consoleTextView.textStorage appendAttributedString:attrString];
    
    NSLog(@"%@", displayString);
    
}

- (void)sendMessage {
    if(FLAG != 2){
        NSString *notDeviceConnect = @"You are not connect device.\n";
        NSLog(@"%@", notDeviceConnect);
        NSAttributedString *attrErrorText = [[NSAttributedString alloc] initWithString:notDeviceConnect];
        [__consoleTextView.textStorage appendAttributedString:attrErrorText];
        return;
    }
    int maxSize = 1024;
    char readBuff[maxSize];
    memset(readBuff,0,sizeof(readBuff));
    
    NSString *inputText = [__sendLabel stringValue];
    if([inputText isEqual:@""]) {
        NSLog(@"empty input will not send.");
        return;
    }
    
    //char *inputCharText = (char *)[inputText cStringUsingEncoding:NSASCIIStringEncoding];
    char *inputCharText = (char *)[inputText UTF8String];
    strcat(inputCharText,"\r\n\0");
    NSLog(@"%s", inputCharText);
    
    ssize_t inputLength = strlen(inputCharText);
    size_t outputLength = 1024;
    
    [serial serialWrite:fd andBuff:inputCharText andBuffLength:inputLength];
    NSLog(@"send: %@", inputText);
    
    sleep(1);
    
    [serial serialRead:fd andBuff:readBuff andBuffLength:outputLength];
    
    for(int i=0;i<outputLength;i++){
        printf("%c",readBuff[i]);
    }
    NSLog(@"%zu", outputLength);
    
    NSString *outString = [NSString stringWithUTF8String:readBuff];
    if([outString isEqual:@""]) {
        outString = @"Nothing reply.\n";
    }
    NSLog(@"%@", outString);
    
    NSAttributedString *attrInputText = [[NSAttributedString alloc] initWithString:outString];
    [__consoleTextView.textStorage appendAttributedString:attrInputText];
    
}

@end
